package com.da.lon.wang.xlg.fragment;

import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.adapter.HomeProductAdapter;
import com.da.lon.wang.xlg.bean.HomeResultBean;
import com.da.lon.wang.xlg.bean.ProductBean;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.pulltorefresh.library.PullToRefreshBase;
import com.da.lon.wang.xlg.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.da.lon.wang.xlg.pulltorefresh.library.PullToRefreshListView;
import com.da.lon.wang.xlg.util.LogUtils;
import com.da.lon.wang.xlg.util.SaveObjectUtils;
import com.da.lon.wang.xlg.util.Utils;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.umeng.analytics.MobclickAgent;

import net.tsz.afinal.http.AjaxParams;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;


public class HomeFragment extends BaseFragment implements
        OnRefreshListener<ListView>, OnClickListener {
    protected Timer timer;
    ArrayList<ProductBean> productList = new ArrayList<ProductBean>();
    String jsonStr;
    private PullToRefreshListView homeList;
    private boolean showed = false;
    private View view;
    private ImageView frushImageView;
    private LinearLayout homeLayout;
    private HomeProductAdapter adapter;
    private HttpLoader<HomeResultBean> loader;
    private SaveObjectUtils object_cache_utils;
    private int time = 10;
    private Handler vpHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (adapter.getViewHolder() != null
                    && adapter.getViewHolder().getViewPager() != null
                    && msg.what == 0) {
                vpHandler.removeMessages(0);
                int currentItem = adapter.getViewHolder().getViewPager()
                        .getCurrentItem();
                currentItem++;
                // LogUtils.v("currentItem:"+currentItem);
                adapter.getViewHolder().getViewPager()
                        .setCurrentItem(currentItem, true);
                vpHandler.sendEmptyMessageDelayed(0, 5000);
            } else if (msg.what == 1) {
                if (homeList != null) {
                    homeList.onRefreshComplete();
                }
            } else if (adapter.getSkill_holder() != null
                    && adapter.getSkill_holder().getTimedown_hour() != null
                    && msg.what == XLGConstants.TIMEDOWN) {
                if ((long) msg.obj == 0L) {
                    time = 5;
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        public void run() {
                            time--;
                            LogUtils.v("刷新HomeFragment" + time);
                            if (time == 0) {
                                timer.cancel();
                                getData();
                            }
                        }
                    }, 0, 500);
                }

                Utils.showTimeDownView((long) msg.obj, adapter
                        .getSkill_holder().getTimedown_hour(), adapter
                        .getSkill_holder().getTimedown_min(), adapter
                        .getSkill_holder().getTimedown_second());
            }

        }

        ;
    };
    private int timeCount = 0;

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("HomeFragment");
        MobclickAgent.onResume(getActivity());
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("HomeFragment");
        MobclickAgent.onPause(getActivity());
    }

    @Override
    protected View inflateView(LayoutInflater inflater, ViewGroup var2) {
        view = inflater.inflate(R.layout.ocoffee_home_fragment, null);
        return view;
    }

    @Override
    protected void initView() {
        try {
            object_cache_utils = new SaveObjectUtils(getActivity(), "home_cache");
            registerBaseReceiver();
            frushImageView = (ImageView) view.findViewById(R.id.frush_img);
            frushImageView.setOnClickListener(this);
            homeLayout = (LinearLayout) view
                    .findViewById(R.id.ouka_home_content);

            homeList = (PullToRefreshListView) view
                    .findViewById(R.id.home_list);
            homeList.setOnRefreshListener(this);
            adapter = new HomeProductAdapter(null, getActivity(), vpHandler);
            homeList.setAdapter(adapter);
            if (MyApplication.isNetworkAvailable(getActivity())) {
                getData();
                homeLayout.setVisibility(View.VISIBLE);
                frushImageView.setVisibility(View.GONE);
            } else {
                HomeResultBean homeResultBean = object_cache_utils.getObject(
                        "home_data", HomeResultBean.class);
                if (homeResultBean != null) {
                    homeLayout.setVisibility(View.VISIBLE);
                    frushImageView.setVisibility(View.GONE);
                    adapter.refreshList(homeResultBean.getResult().getData());
                } else {
                    homeLayout.setVisibility(View.GONE);
                    frushImageView.setVisibility(View.VISIBLE);
                }
            }

            {
                HttpLoader httpLoader = new HttpLoader<>(getActivity(),
                        "http://api.sk.osell.com/" + "App-showList", HomeResultBean.class,
                        30 * 1000);
                AjaxParams params = new AjaxParams();
                params.put("token", XLGDataUtils.encrypt2MD5("App" + "2015#$%" + "showList"));
                params.put("cid", "40");

                httpLoader.loadData(params);
            }
//			toast();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getData() {
        try {
            loader = new HttpLoader<>(getActivity(),
                    XLGConstants.URL + "Index-index", HomeResultBean.class,
                    30 * 1000);
            AjaxParams params = new AjaxParams();
            params.put("token", XLGDataUtils.encrypt2MD5("Index" + "2015#$%"
                    + "index"));
            params.put("version", "21");

            loader.loadData(params);
            loader.setManagerListener(new OnWebLoadListener<HomeResultBean>() {

                @Override
                public void OnStart() {
                    showDialog();
                }

                @Override
                public void OnError(String error) {
                    dismissDialog();
                    vpHandler.sendEmptyMessage(1);
                }

                @Override
                public void onSuccess(HomeResultBean t) {
                    dismissDialog();
                    homeLayout.setVisibility(View.VISIBLE);
                    frushImageView.setVisibility(View.GONE);
                    vpHandler.sendEmptyMessage(1);
                    if (t != null && t.getCode().equals("000000")) {
                        showed = true;
                        adapter.refreshList(t.getResult().getData());
                        // 首页数据缓存
//                        PreferenceUtils.getInstance().SetSettingInt("version",
//                                Integer.parseInt(t.getResult().getVesion()));
                        object_cache_utils.setObject("home_data", t);
                    }

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        try {
            if (!MyApplication.isNetworkAvailable(getActivity())) {
                Toast.makeText(getActivity(), "网络连接失败", Toast.LENGTH_SHORT)
                        .show();
                vpHandler.sendEmptyMessage(1);
            } else {
                if (timeCount == 0) {
                    getData();
                    new Thread() {
                        public void run() {
                            while (timeCount++ < 6) {
                                try {
                                    Thread.sleep(1000L);
                                    if (timeCount > 4) {
                                        vpHandler.sendEmptyMessage(1);
                                    }
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            timeCount = 0;
                        }

                        ;
                    }.start();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.frush_img:
                if (!MyApplication.isNetworkAvailable(getActivity())) {
                    showDialog();
                    homeLayout.setVisibility(View.GONE);
                    frushImageView.setVisibility(View.VISIBLE);
                    new Thread() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(2000);
                                dismissDialog();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
                } else {
                    getData();
                }

                break;

            default:
                break;
        }
    }

    @Override
    protected void RefreshData() {
        getData();

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }
}
